package com.ubi.core.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ubi.core.framework.exception.RuntimeIOException;

import java.io.IOException;

public class JsonConverter {

    protected final ObjectMapper objectMapper;

    public JsonConverter() {
        objectMapper = ObjectMapperCreator.createDefaultObjectMapper();
    }

    public JsonConverter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public String toJson(Object value) {
        if (value == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeIOException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T toObject(String json, Class<T> beanClass) {
        if (json == null) {
            return null;
        }
        try {
            return objectMapper.readValue(json, beanClass);
        } catch (IOException e) {
            throw new RuntimeIOException(e);
        }
    }

    /**
     * json格式的数据转换成为特定的Collection<T>对象
     * @param beanClass       具体的集合对象
     * @param collectionClass 集合类型, 比如List
     */
    public <T, V> V toObject(String json, Class<T> beanClass, Class<V> collectionClass) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, beanClass);
        if (json == null) {
            return null;
        }
        try {
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            throw new RuntimeIOException(e);
        }
    }

}
